package cntv.player.core.util;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

/**
 * 防止重复弹出同样的toast
 * 
 * @author zengliang
 * 
 */
public class ToastUtil {

	public static final int LENGTH_SHORT = Toast.LENGTH_SHORT;
	public static final int LENGTH_LONG = Toast.LENGTH_LONG;

	private static Toast mToast;
	private static Handler handler = new Handler();

	private static Runnable run = new Runnable() {
		public void run() {
			mToast.cancel();
		}
	};

	private static void toast(Context context, CharSequence msg, int duration) {
		if (null == context) {
			return;
		}
		handler.removeCallbacks(run);
		// handler的duration不能直接对应Toast的常量时长，在此针对Toast的常量相应定义时长
		switch (duration) {
		case LENGTH_SHORT:// Toast.LENGTH_SHORT值为0，对应的持续时间大概为1s
			duration = 1000;
			break;
		case LENGTH_LONG:// Toast.LENGTH_LONG值为1，对应的持续时间大概为3s
			duration = 3000;
			break;
		default:
			break;
		}
		if (null != mToast) {
			mToast.setText(msg);
		} else {
			mToast = Toast.makeText(context, msg, duration);
		}
		handler.postDelayed(run, duration);
		mToast.show();
	}

	/**
	 * 弹出Toast
	 * 
	 * @param context
	 *            弹出Toast的上下文
	 * @param msg
	 *            弹出Toast的内容
	 * @param duration
	 *            弹出Toast的持续时间
	 */
	public static void showToast(Context context, CharSequence msg, int duration) {
		if (null == context) {
			return;
		}
		if (0 > duration) {
			duration = LENGTH_SHORT;
		}
		toast(context, msg, duration);
	}

	/**
	 * 弹出Toast
	 * 
	 * @param context
	 *            弹出Toast的上下文
	 * @param msg
	 *            弹出Toast的内容的资源ID
	 * @param duration
	 *            弹出Toast的持续时间
	 */
	public static void showToast(Context context, int resId, int duration) {
		if (null == context) {
			return;
		}
		if (0 > duration) {
			duration = LENGTH_SHORT;
		}
		toast(context, context.getResources().getString(resId), duration);
	}
}
